#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
格式转换选项卡 - 负责文件格式转换功能的GUI界面
"""

import os
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path

from core import converter
from gui.base_tab import BaseTab

class ConverterTab(BaseTab):
    """格式转换选项卡"""
    
    def __init__(self, parent):
        super().__init__(parent)
        
        # 创建变量
        self.directory_var = tk.StringVar()
        self.output_dir_var = tk.StringVar()
        self.from_format_var = tk.StringVar()
        self.to_format_var = tk.StringVar()
        self.conversion_type_var = tk.StringVar(value="image")
        self.recursive_var = tk.BooleanVar(value=True)
        
        # 图片选项变量
        self.quality_var = tk.StringVar(value="90")
        
        # 音频选项变量
        self.audio_bitrate_var = tk.StringVar(value="128k")
        
        # 视频选项变量
        self.video_bitrate_var = tk.StringVar(value="1M")
        self.resolution_var = tk.StringVar(value="1280x720")
        
        # 创建界面元素
        self.create_widgets()
        
        # 绑定事件
        self.conversion_type_var.trace("w", self.on_conversion_type_changed)
        
        # 初始状态设置
        self.on_conversion_type_changed()
        self.set_format_options("image")
    
    def create_widgets(self):
        """创建界面元素"""
        # 创建主框架
        main_frame = ttk.Frame(self)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 源目录选择
        source_frame = ttk.LabelFrame(main_frame, text="源目录")
        source_frame.pack(fill=tk.X, pady=5)
        
        ttk.Entry(source_frame, textvariable=self.directory_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        ttk.Button(source_frame, text="浏览...", command=self.browse_source_dir).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 输出目录选择（可选）
        output_frame = ttk.LabelFrame(main_frame, text="输出目录（可选，默认在源目录中生成）")
        output_frame.pack(fill=tk.X, pady=5)
        
        ttk.Entry(output_frame, textvariable=self.output_dir_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        ttk.Button(output_frame, text="浏览...", command=self.browse_output_dir).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 转换类型选择
        type_frame = ttk.LabelFrame(main_frame, text="转换类型")
        type_frame.pack(fill=tk.X, pady=5)
        
        ttk.Radiobutton(type_frame, text="图片格式转换", variable=self.conversion_type_var, value="image").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(type_frame, text="音频格式转换", variable=self.conversion_type_var, value="audio").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(type_frame, text="视频格式转换", variable=self.conversion_type_var, value="video").pack(anchor=tk.W, padx=5, pady=2)
        ttk.Radiobutton(type_frame, text="文档格式转换", variable=self.conversion_type_var, value="document").pack(anchor=tk.W, padx=5, pady=2)
        
        # 基本选项
        options_frame = ttk.LabelFrame(main_frame, text="基本选项")
        options_frame.pack(fill=tk.X, pady=5)
        
        # 创建格式选择区域
        formats_frame = ttk.Frame(options_frame)
        formats_frame.pack(fill=tk.X, expand=True, padx=5, pady=5)
        
        ttk.Label(formats_frame, text="源格式:").pack(side=tk.LEFT, padx=5)
        self.from_format_combo = ttk.Combobox(formats_frame, textvariable=self.from_format_var, width=10)
        self.from_format_combo.pack(side=tk.LEFT, padx=5)
        
        ttk.Label(formats_frame, text="目标格式:").pack(side=tk.LEFT, padx=5)
        self.to_format_combo = ttk.Combobox(formats_frame, textvariable=self.to_format_var, width=10)
        self.to_format_combo.pack(side=tk.LEFT, padx=5)
        
        # 递归选项
        ttk.Checkbutton(options_frame, text="递归处理子目录", variable=self.recursive_var).pack(anchor=tk.W, padx=5, pady=2)
        
        # 高级选项框架 - 根据转换类型动态显示
        self.advanced_frame = ttk.LabelFrame(main_frame, text="高级选项")
        
        # 图片选项
        self.image_options_frame = ttk.Frame(self.advanced_frame)
        ttk.Label(self.image_options_frame, text="图片质量 (1-100):").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Entry(self.image_options_frame, textvariable=self.quality_var, width=5).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 音频选项
        self.audio_options_frame = ttk.Frame(self.advanced_frame)
        ttk.Label(self.audio_options_frame, text="音频比特率:").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Combobox(self.audio_options_frame, textvariable=self.audio_bitrate_var, 
                   values=["64k", "128k", "192k", "256k", "320k"], width=10).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 视频选项
        self.video_options_frame = ttk.Frame(self.advanced_frame)
        
        ttk.Label(self.video_options_frame, text="视频比特率:").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Combobox(self.video_options_frame, textvariable=self.video_bitrate_var, 
                   values=["500k", "1M", "2M", "5M", "10M"], width=10).pack(side=tk.LEFT, padx=5, pady=5)
        
        ttk.Label(self.video_options_frame, text="分辨率:").pack(side=tk.LEFT, padx=5, pady=5)
        ttk.Combobox(self.video_options_frame, textvariable=self.resolution_var, 
                   values=["640x480", "1280x720", "1920x1080", "3840x2160"], width=10).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 执行按钮和进度区
        action_frame = ttk.Frame(main_frame)
        action_frame.pack(fill=tk.X, pady=10)
        
        self.progress_var = tk.StringVar(value="")
        ttk.Label(action_frame, textvariable=self.progress_var).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        
        self.convert_button = ttk.Button(action_frame, text="转换", command=self.convert_files)
        self.convert_button.pack(side=tk.RIGHT, padx=5)
        
        # 结果显示区域
        results_frame = ttk.LabelFrame(main_frame, text="转换结果")
        results_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.results_text = self.create_text_display(results_frame, height=10)
    
    def on_conversion_type_changed(self, *args):
        """转换类型变化时的处理"""
        conversion_type = self.conversion_type_var.get()
        
        # 隐藏所有高级选项
        self.advanced_frame.pack_forget()
        if hasattr(self, 'image_options_frame'):
            self.image_options_frame.pack_forget()
        if hasattr(self, 'audio_options_frame'):
            self.audio_options_frame.pack_forget()
        if hasattr(self, 'video_options_frame'):
            self.video_options_frame.pack_forget()
        
        # 更新格式选项
        self.set_format_options(conversion_type)
        
        # 显示相应的高级选项
        if conversion_type == "image":
            self.advanced_frame.pack(fill=tk.X, pady=5)
            self.image_options_frame.pack(fill=tk.X, padx=5, pady=5)
        elif conversion_type == "audio":
            self.advanced_frame.pack(fill=tk.X, pady=5)
            self.audio_options_frame.pack(fill=tk.X, padx=5, pady=5)
        elif conversion_type == "video":
            self.advanced_frame.pack(fill=tk.X, pady=5)
            self.video_options_frame.pack(fill=tk.X, padx=5, pady=5)
    
    def set_format_options(self, conversion_type):
        """设置格式选项"""
        if conversion_type == "image":
            from_formats = ["jpg", "png", "gif", "bmp", "webp", "tiff"]
            to_formats = ["jpg", "png", "gif", "bmp", "webp", "tiff"]
            
            self.from_format_combo['values'] = from_formats
            self.to_format_combo['values'] = to_formats
            
            if not self.from_format_var.get() in from_formats:
                self.from_format_var.set("jpg")
            if not self.to_format_var.get() in to_formats:
                self.to_format_var.set("png")
            
        elif conversion_type == "audio":
            from_formats = ["mp3", "wav", "ogg", "flac", "aac", "m4a"]
            to_formats = ["mp3", "wav", "ogg", "flac", "aac", "m4a"]
            
            self.from_format_combo['values'] = from_formats
            self.to_format_combo['values'] = to_formats
            
            if not self.from_format_var.get() in from_formats:
                self.from_format_var.set("mp3")
            if not self.to_format_var.get() in to_formats:
                self.to_format_var.set("wav")
            
        elif conversion_type == "video":
            from_formats = ["mp4", "avi", "mkv", "mov", "wmv", "webm"]
            to_formats = ["mp4", "avi", "mkv", "mov", "wmv", "webm"]
            
            self.from_format_combo['values'] = from_formats
            self.to_format_combo['values'] = to_formats
            
            if not self.from_format_var.get() in from_formats:
                self.from_format_var.set("mp4")
            if not self.to_format_var.get() in to_formats:
                self.to_format_var.set("mkv")
            
        elif conversion_type == "document":
            from_formats = ["docx", "pdf"]
            to_formats = ["pdf", "docx"]
            
            self.from_format_combo['values'] = from_formats
            self.to_format_combo['values'] = to_formats
            
            if not self.from_format_var.get() in from_formats:
                self.from_format_var.set("docx")
            if not self.to_format_var.get() in to_formats:
                self.to_format_var.set("pdf")
    
    def browse_source_dir(self):
        """浏览选择源目录"""
        self.browse_directory(title="选择源目录", var=self.directory_var)
    
    def browse_output_dir(self):
        """浏览选择输出目录"""
        self.browse_directory(title="选择输出目录", var=self.output_dir_var)
    
    def convert_files(self):
        """执行文件转换"""
        # 获取参数
        directory = self.directory_var.get()
        output_dir = self.output_dir_var.get() or None
        conversion_type = self.conversion_type_var.get()
        from_format = self.from_format_var.get()
        to_format = self.to_format_var.get()
        recursive = self.recursive_var.get()
        
        # 验证参数
        if not self.validate_directory(directory):
            return
        
        if output_dir and not self.validate_directory(output_dir, create_if_missing=True):
            return
        
        if not from_format or not to_format:
            messagebox.showerror("错误", "请选择源格式和目标格式")
            return
        
        # 获取类型特定的参数
        quality = None
        audio_bitrate = None
        video_bitrate = None
        resolution = None
        
        if conversion_type == "image":
            try:
                quality = int(self.quality_var.get())
                if quality < 1 or quality > 100:
                    raise ValueError("质量值必须在1-100之间")
            except ValueError as e:
                messagebox.showerror("错误", f"无效的质量值: {e}")
                return
                
        elif conversion_type == "audio":
            audio_bitrate = self.audio_bitrate_var.get()
            
        elif conversion_type == "video":
            video_bitrate = self.video_bitrate_var.get()
            resolution = self.resolution_var.get()
        
        # 清空结果区域
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        self.results_text.config(state=tk.DISABLED)
        
        # 更新进度显示
        self.progress_var.set("正在转换...")
        
        # 禁用转换按钮
        self.convert_button.config(state=tk.DISABLED)
        
        # 在线程中执行文件转换
        self.run_in_thread(
            self._convert_files_thread, 
            args=(directory, output_dir, conversion_type, from_format, to_format, recursive, 
                 quality, audio_bitrate, video_bitrate, resolution),
            on_complete=self._on_conversion_complete
        )
    
    def _convert_files_thread(self, directory, output_dir, conversion_type, from_format, to_format, 
                           recursive, quality, audio_bitrate, video_bitrate, resolution):
        """在线程中执行文件转换"""
        converted_map = {}
        
        try:
            # 根据转换类型执行相应的转换
            if conversion_type == "image":
                # 检查是否安装了Pillow
                try:
                    import PIL
                except ImportError:
                    raise ImportError("需要安装Pillow库: pip install Pillow")
                
                converted_map = converter.batch_convert_images(
                    directory, from_format, to_format,
                    recursive=recursive, output_dir=output_dir,
                    quality=quality
                )
            
            elif conversion_type == "audio":
                # 检查是否安装了ffmpeg
                if not converter.check_ffmpeg():
                    raise EnvironmentError("需要安装ffmpeg: https://ffmpeg.org/download.html")
                
                converted_map = converter.batch_convert_audio(
                    directory, from_format, to_format,
                    recursive=recursive, output_dir=output_dir,
                    bitrate=audio_bitrate
                )
            
            elif conversion_type == "video":
                # 检查是否安装了ffmpeg
                if not converter.check_ffmpeg():
                    raise EnvironmentError("需要安装ffmpeg: https://ffmpeg.org/download.html")
                
                converted_map = converter.batch_convert_video(
                    directory, from_format, to_format,
                    recursive=recursive, output_dir=output_dir,
                    video_bitrate=video_bitrate,
                    audio_bitrate=audio_bitrate,
                    resolution=resolution
                )
            
            elif conversion_type == "document":
                # 检查是否安装了文档处理库
                converted_map = converter.batch_convert_documents(
                    directory, from_format, to_format,
                    recursive=recursive, output_dir=output_dir
                )
            
            return converted_map
        
        except Exception as e:
            messagebox.showerror("错误", f"文件转换出错: {str(e)}")
            return {}
    
    def _on_conversion_complete(self, converted_map):
        """转换完成后的回调"""
        # 恢复转换按钮
        self.convert_button.config(state=tk.NORMAL)
        
        if not converted_map:
            self.progress_var.set("未找到匹配的文件进行转换")
            return
        
        # 更新进度显示
        self.progress_var.set(f"转换完成，共处理 {len(converted_map)} 个文件")
        
        # 更新结果区域
        self.results_text.config(state=tk.NORMAL)
        self.results_text.delete(1.0, tk.END)
        
        self.results_text.insert(tk.END, f"已转换 {len(converted_map)} 个文件:\n\n")
        
        # 显示所有转换的文件
        for i, (source, target) in enumerate(converted_map.items()):
            # 显示路径可能很长，只显示相对路径或文件名
            source_path = Path(source)
            target_path = Path(target)
            
            self.results_text.insert(tk.END, f"{i+1}. {source_path.name} -> {target_path.name}\n")
        
        self.results_text.config(state=tk.DISABLED) 